<template>
  <basic-container>
    <SzListHead v-model:search="crmOption.search"
                :create-fun="createClick"
                :addBtnText="addBtnText"
                :searchPlaceHolder="searchPlaceHolder"
                v-on:on-search="listHeadSearch"
                v-on:on-import-done="importDone"
                v-on:on-export="listHeadExport">
      <template v-slot:ft>
        <slot name="listHeadSlot"></slot>
      </template>
    </SzListHead>
    <div class="crm-container">
      <SzTableHead ref="crmTableHead"
                   :crm-type="crmOption.crmType"
                   :sort-data="tableHeadOption.sortData"
                   @filter="tableHeadOnFilter"
                   @handle="tableHeadOnHandle"
                   @scene="tableHeadOnScene"></SzTableHead>

      <slot name="table"></slot>
      <SzTable v-if="!$slots.table" :cellClassName="cellClassName" :header-cell-class-name="headerCellClassName"
               :tableHeight="crmOption.tableHeight"
               @setSelection="setSelections"
               @getFieldList="getFieldList"
               @getList="onLoad"
               @createClick="createClick"></SzTable>

      <div class="p-container">
        <slot name="pagination-left"></slot>
        <SzPagination v-model:pageSize=paginationOption.pageSize
                      v-model:currentPage=paginationOption.currentPage
                      v-model:total="paginationOption.total">
        </SzPagination>
        <slot name="pagination-right"></slot>
      </div>
    </div>

    <!--详情-->
    <slot name="detail" :crmOption="crmOption"
          :elTableOption="elTableOption"
          :fieldAndListOption="fieldAndListOption"
          :handleHandle="handleHandle"
          :crmOptionChange="crmOptionChange"></slot>
    <!--新建-->
    <slot name="create" :crmOption="crmOption"
          :elTableOption="elTableOption"
          :fieldAndListOption="fieldAndListOption"
          :handleHandle="handleHandle"
          :crmOptionChange="crmOptionChange"></slot>
    <slot name="eof"></slot>
  </basic-container>
</template>

<script setup>
import {nextTick, onMounted, ref, watch} from "vue";
import {
  crmConfigKey, crmOptionChangeKey,
  crmOptionKey, elTableOptionChangeKey,
  elTableOptionKey,
  fieldAndListOptionKey, mainTableKey,
  pageOptionKey, tableHeadIsSeasKey,
  tableHeadOptionKey, tableHeadPoolIdKey
} from "/src/views/crm/componentsNew/SzCrud/keys";
import crmTypeModel from "/src/views/crm/model/crmTypeModel.js";
import {
  crmCustomerExcelAllExportAPI,
  crmCustomerPoolExcelAllExport,
} from "/src/api/crm/customer.js";
import {crmLeadsExcelAllExportAPI} from "@/api/crm/leads.js";
import {crmContactsExcelAllExportAPI} from "@/api/crm/contacts.js";
import {crmBusinessExcelAllExportAPI} from "@/api/crm/business.js";
import {crmContractExcelAllExportAPI} from "@/api/crm/contract.js";
import {crmReceivablesExcelAllExportAPI} from "@/api/crm/receivables.js";
import {crmProductExcelAllExportAPI} from "@/api/crm/product.js";
import {crmInvoiceExcelAllExportAPI} from "@/api/crm/invoice.js";
import {crmReceivablesPlanExcelAllExportAPI} from "@/api/crm/receivablesPlan.js";
import {ElLoading} from "element-plus";
import {downloadExcelWithResData} from "utils";
import {useCrmAllCreate} from "@/views/crm/hooks/create/useCrmAllCreate.js";
import {useTableIndex} from "@/views/crm/hooks/index/useTableIndex.js";
import SzListHead from "@/views/crm/componentsNew/SzCrud/listHead/szListHead.vue";
import SzTable from "@/views/crm/componentsNew/SzCrud/table/szTable.vue";
import SzTableHead from "@/views/crm/componentsNew/SzCrud/tableHead/szTableHead.vue";
import SzPagination from "@/views/crm/componentsNew/SzCrud/pagination/SzPagination.vue";

defineOptions({
  /** 客户管理 的 线索列表 */
  name: 'SzCrudSingle',
})


const properties = defineProps({
  crmType: {
    type: String,
    default: "customer"
  },
  createType: {
    type: String,
    default: "customer"
  },
  addBtnText: {
    type: String,
    default: ''
  },
  searchPlaceHolder: {
    type: String,
    default: ''
  },
  // 筛选选择的数据
  selectedData: Array,
  // 在两个地方可能执行，第一；listHead中的新建按钮。第二：如果列表空白，显示的新建按钮
  createFun: Function,
  // 针对某些字段的特殊样式设置，主要是名称这一列
  cellClassName: Function,
  headerCellClassName: Function
})

const emits = defineEmits(['onLoad'])

function onLoad() {
  // 使用分页数参数去获取数据
  getList()
  emits('onLoad', '');
}

//todo whf 要想将getList和getFieldList解耦，需要支持从外部传入fieldList和dataList
const {
  crm,
  config,
  crmOption,
  elTableOption,
  tableHeadOption,
  fieldAndListOption,
  paginationOption,
  getList, getFieldList
} = useTableIndex()

function crmOptionChange(key, val) {
  crmOption[key] = val
}

function elTableOptionChange(key, value) {
  elTableOption[key] = value
}

onMounted(() => {
  crmOption.crmType = properties.crmType
  crmOption.createType = properties.createType
  onLoad()
})
watch(() => properties.crmType, (val) => {
  crmOption.crmType = val
})
watch(() => properties.createType, (val) => {
  crmOption.createType = val
})


provide(crmConfigKey, config)
provide(crmOptionKey, crmOption)
provide(crmOptionChangeKey, crmOptionChange)
provide(tableHeadOptionKey, tableHeadOption)
provide(elTableOptionKey, elTableOption)
provide(elTableOptionChangeKey, elTableOptionChange)
provide(fieldAndListOptionKey, fieldAndListOption)
provide(pageOptionKey, paginationOption)

const {saveSuccess, handleHandle} = useCrmAllCreate(crmOption)


/**
 * 字段排序
 */
function sortChange(column, prop, order) {
  paginationOption.currentPage = 1
  tableHeadOption.sortData = column || {}
  onLoad()
}


watch(() => paginationOption, (val) => {
  // 这里应该发送消息事件
  onLoad()
}, {
  deep: true
})


/**
 * 新建点击
 */
function createClick() {
  console.log("createClick")
  if (properties.createFun) {
    console.log("createClick fun")
    properties.createFun()
  } else {
    console.log("createClick else")
    crmOption.createShow = true
  }

}


// 新建或者导入成功后的调用
function importDone(data) {
  if (data.type === 'import-crm') {
    // 重新请求第一页数据
    // 设置currentPage为
    paginationOption.currentPage = 1
    // 刷新页面
    onLoad()
  }
}

function listHeadSearch(value) {
  // 设置currentPage为
  paginationOption.currentPage = 1
  crmOption.search = value
  const fieldList = fieldAndListOption.fieldList
  if (fieldList.length) {
    // 刷新页面
    onLoad()
  }
}

function listHeadExport() {
  // 可考虑将params的组合放到这里
  const params = {
    search: crmOption.search,
    type: crmOption.isSeas ? crmTypeModel.pool : crmTypeModel[crmType.value] // 9是公海
  }
  if (tableHeadOption.sceneId) {
    params.sceneId = tableHeadOption.sceneId
  }

  // 公海切换
  if (tableHeadOption.poolId) {
    params.poolId = tableHeadOption.poolId
  }

  if (tableHeadOption.filterObj && tableHeadOption.filterObj.length > 0) {
    params.searchList = tableHeadOption.filterObj
  }

  let request = null
  // 公海的请求
  if (crmOption.isSeas) {
    request = crmCustomerPoolExcelAllExport
  } else {
    request = {
      customer: crmCustomerExcelAllExportAPI,
      leads: crmLeadsExcelAllExportAPI,
      contacts: crmContactsExcelAllExportAPI,
      business: crmBusinessExcelAllExportAPI,
      contract: crmContractExcelAllExportAPI,
      receivables: crmReceivablesExcelAllExportAPI,
      product: crmProductExcelAllExportAPI,
      invoice: crmInvoiceExcelAllExportAPI,
      receivablesPlan: crmReceivablesPlanExcelAllExportAPI
    }[crmOption.crmType]
  }
  const loading = ElLoading.service({fullscreen: true, text: '导出中...'})
  request(params).then(res => {
    downloadExcelWithResData(res)
    loading.close()
  }).catch((r) => {
    console.log("r", r)
    loading.close()
  })
}


function tableHeadOnFilter(data) {
  // 设置sendId和sceneName
  tableHeadOption.filterObj = data

  updateTableHeight()

  // 设置currentPage为
  paginationOption.currentPage = 1
  onLoad();
}

/**
 * 筛选后的操作。
 * 选择记录后，tableHead就显示一些操作，类似详情页面中的操作，包括转移、放入公海、添加团队成员等等。
 * 这里处理的是对应操作的相应
 * 在TableHead中，处理clear-sort，此时会清空排序规则。同时设置排序数据，并请求列表数据。
 * @param {*} data
 */
function tableHeadOnHandle(eleTable, data) {
  if (data.type == 'clear-sort') {
    getMainTable().clearSort()
    sortChange()
  } else {
    // 只有不是选择效果，有特殊操作，清空勾选
    if (!config.value.isSelect) {
      getMainTable().clearSelection()
    }
    onLoad()
  }
}

function tableHeadOnScene(data) {
  // 设置sendId和sceneName
  tableHeadOption.sceneId = data.id
  tableHeadOption.sceneName = data.name
  // 设置currentPage为1
  paginationOption.currentPage = 1
  getFieldList()
  onLoad()
}


/**
 * 设置selections值
 */
function setSelections(data) {
  // const mainTable = getMainTable()
  const mainTable = mainTableRef.value
  mainTable.clearSelection()
  nextTick(() => {
    data.forEach(item => {
      mainTable.toggleRowSelection(item)
    })
  }).then(r => {
  })
}

const mainTableRef = ref();

function getMainTable(ele) {
  mainTableRef.value = ele
}

provide(mainTableKey, getMainTable)

function updateTableHeight() {
  // 如果config中配置了tableHeight
  const filterObj = tableHeadOption.filterObj
  // 如果传入了tableHeigh，使用传入值
  if (crmOption.tableHeight != null && crmOption.tableHeight == 0) {
    nextTick(() => {
      // filterObj在CrmTableHeadHook中
      crmOption.tableHeight = filterObj.length > 0
          ? crmOption.tableHeight - 60
          : crmOption.tableHeight
    }).then(r => {
      console.log(r)
    })
  } else {
    // 如果没有传入值，使用窗口的高度
    let offsetHei = document.documentElement.clientHeight
    let removeHeight = filterObj.length > 0 ? 295 : 235
    crmOption.tableHeight = offsetHei - removeHeight
  }
}


defineExpose({
  config,
  crmOption,
  elTableOption,
  tableHeadOption,
  fieldAndListOption,
  pageOption: paginationOption,
})


</script>

<style lang="scss" scoped>
@import '../../styles/table';
</style>
